package com.ruoyi.chatAi.controller;

import com.ruoyi.chatAi.domain.ChatMessage;
import com.ruoyi.chatAi.service.ChatMessageService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天消息控制器
 *
 * @author ruoyi
 */
@Anonymous
@RestController
@RequestMapping("/chat/messages")
public class ChatMessageController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ChatMessageController.class);

    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 获取指定会话的所有消息
     */
    @GetMapping
    public AjaxResult getMessagesBySessionId(@RequestParam("sessionId") String sessionId) {
        try {
            if (sessionId == null) {
                return AjaxResult.error("会话ID不能为空");
            }

            List<ChatMessage> messages = chatMessageService.selectChatMessagesBySessionId(sessionId);
            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("获取会话消息失败: ", e);
            return AjaxResult.error("获取会话消息失败: " + e.getMessage());
        }
    }

    /**
     * 查询聊天消息列表（分页）
     */
    @PreAuthorize("@ss.hasPermi('chatAi:message:list')")
    @GetMapping("/list")
    public TableDataInfo listMessages(ChatMessage chatMessage) {
        try {
            startPage();
            List<ChatMessage> list = chatMessageService.selectChatMessageList(chatMessage);
            return getDataTable(list);
        } catch (Exception e) {
            log.error("查询消息列表失败: ", e);
            throw e;
        }
    }

    /**
     * 获取聊天消息详细信息
     */
    @PreAuthorize("@ss.hasPermi('chatAi:message:query')")
    @GetMapping("/{messageId}")
    public AjaxResult getMessageInfo(@PathVariable("messageId") Long messageId) {
        try {
            return AjaxResult.success(chatMessageService.selectChatMessageById(messageId));
        } catch (Exception e) {
            log.error("获取消息详情失败: ", e);
            return AjaxResult.error("获取消息详情失败: " + e.getMessage());
        }
    }

    /**
     * 新增单条聊天消息
     */
    @PostMapping
    public AjaxResult addMessage(@RequestBody ChatMessage chatMessage) {
        try {
            if (chatMessage.getUserId() == null) {
                chatMessage.setUserId(SecurityUtils.getUserId());
            }
            chatMessage.setCreateBy(SecurityUtils.getUsername());

            int result = chatMessageService.insertChatMessage(chatMessage);
            if (result > 0) {
                return AjaxResult.success("添加成功", chatMessage.getMessageId());
            } else {
                return AjaxResult.error("添加失败");
            }
        } catch (Exception e) {
            log.error("新增消息失败: ", e);
            return AjaxResult.error("新增消息失败: " + e.getMessage());
        }
    }

    /**
     * 修改聊天消息
     */
    @PreAuthorize("@ss.hasPermi('chatAi:message:edit')")
    @PutMapping
    public AjaxResult editMessage(@RequestBody ChatMessage chatMessage) {
        try {
            chatMessage.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(chatMessageService.updateChatMessage(chatMessage));
        } catch (Exception e) {
            log.error("修改消息失败: ", e);
            return AjaxResult.error("修改消息失败: " + e.getMessage());
        }
    }

    /**
     * 删除聊天消息
     */
    @PreAuthorize("@ss.hasPermi('chatAi:message:remove')")
    @DeleteMapping("/{messageIds}")
    public AjaxResult removeMessages(@PathVariable Long[] messageIds) {
        try {
            return toAjax(chatMessageService.deleteChatMessageByIds(messageIds));
        } catch (Exception e) {
            log.error("删除消息失败: ", e);
            return AjaxResult.error("删除消息失败: " + e.getMessage());
        }
    }

    /**
     * 根据会话ID删除所有消息
     */
    @DeleteMapping("/session/{sessionId}")
    @PreAuthorize("@ss.hasPermi('chatAi:message:remove')")
    public AjaxResult deleteMessagesBySessionId(@PathVariable("sessionId") String sessionId) {
        try {
            return toAjax(chatMessageService.deleteChatMessagesBySessionId(sessionId));
        } catch (Exception e) {
            log.error("删除会话消息失败: ", e);
            return AjaxResult.error("删除会话消息失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户消息数量统计
     */
    @GetMapping("/count")
    public AjaxResult countUserMessages() {
        try {
            Long userId = SecurityUtils.getUserId();
            int count = chatMessageService.countUserMessages(userId);
            return AjaxResult.success(count);
        } catch (Exception e) {
            log.error("获取用户消息数量统计失败: ", e);
            return AjaxResult.error("获取用户消息数量统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取聊天上下文
     */
    @GetMapping("/context/{sessionId}")
    public AjaxResult getConversationContext(@PathVariable("sessionId") String sessionId,
                                             @RequestParam(defaultValue = "10") int maxContextSize) {
        try {
            List<ChatMessage> context = chatMessageService.getConversationContext(sessionId, maxContextSize);
            return AjaxResult.success(context);
        } catch (Exception e) {
            log.error("获取聊天上下文失败: ", e);
            return AjaxResult.error("获取聊天上下文失败: " + e.getMessage());
        }
    }
}